// pages/share/share.js
import { personInfo, getPicQRCode, getUserInfoFromMobile, getCodeByPhone } from '../../api/index'
import { getUserInfo, setUserInfo } from '../../utils/storage'
import { showLoading, showToast, hideLoading } from '../../utils/toast'
import { trackingEventMap, trackingEvent } from '../../utils/tracking'
const globalData = getApp().globalData

Page({

  /**
   * 页面的初始数据
   */
  data: {
    activitySwitch: globalData.activityConfig.activitySwitch,
    inviteQuery: '',
    shareTag: '',
    imageCode: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getPersonInfo()
    this.getUserInfoData()
  },
  async getPersonInfo() {
    let result = await personInfo({ queryType: 2 })
    if (result.inviteUrl) {
      this.setData({
        inviteQuery: result.inviteUrl.split('?')[1]
      })
    }
  },
  // 获取用户信息及分享参数
  async getUserInfoData() {
    let phoneNumber = ''
    if (getUserInfo()) {
      let userInfo = JSON.parse(getUserInfo())
      phoneNumber = userInfo.phoneNumber
    }
    if (!phoneNumber) {
      let result = await getUserInfoFromMobile()
      setUserInfo(JSON.stringify(result))
      phoneNumber = result.phoneNumber
    }

    let tagResult = await getCodeByPhone({
      phone: phoneNumber
    })
    this.setData({
      shareTag: tagResult || ''
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  async imgHandle() {
    if (this.data.imageCode) {
      this.base64ToFilePath(this.data.imageCode)
      return
    }
    try {
      trackingEvent(trackingEventMap.posterGeneration)
      showLoading('生成海报中')
      let inviteQuery = this.data.inviteQuery
      if (this.data.shareTag) {
        inviteQuery = inviteQuery + `&sourceTag=` + this.data.shareTag
      }
      let result = await getPicQRCode({
        // checkPath: false,
        // envVersion: 'trial',
        scene: inviteQuery,
        page: globalData.activityConfig.qrPath
      })
      this.setData({
        imageCode: result.code
      })
      hideLoading()
      this.base64ToFilePath(result.code)
    } catch (error) {
      hideLoading()
    }

  },
  base64ToFilePath(base64data) {//封装的base64转换成临时文件路径的函数
    const base64 = base64data; //base64格式图片
    const time = new Date().getTime();
    const imgPath = wx.env.USER_DATA_PATH + "/" + time + "share_qrcode.png"; //去掉data:image/png;base64,如果图片字符串不含要清空的前缀,可以不执行下行代码.
    const imageData = base64.replace(/^data:image\/\w+;base64,/, "");
    const file = wx.getFileSystemManager();
    file.writeFileSync(imgPath, imageData, "base64");
    wx.showShareImageMenu({ //分享给朋友
      path: imgPath,
      success: (res) => {
        console.log("分享成功：", res);
      },
      fail: (err) => {
        console.log("分享取消：", err);
      },
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    trackingEvent(trackingEventMap.shareForward2)
    globalData.showSwitch = '0'
    let inviteQuery = this.data.inviteQuery
    let shareTag = this.data.shareTag
    let sharePath = globalData.activityConfig.sharePath
    let imageUrl = 'https://psy-public.obs.myhuaweicloud.com/bpai/active/20240331/act006.png'
    let t = Date.now()

    if (globalData.activityConfig.activitySwitch == '1') {
      imageUrl = 'https://psy-public.obs.myhuaweicloud.com/bpai/active/20240520/act005.png'
    }
    if (inviteQuery) {
      if (shareTag) {
        inviteQuery = inviteQuery + `&sourceTag=` + shareTag
      }
      return {
        title: globalData.activityConfig.shareTitle,
        path: `${sharePath}?${inviteQuery}`,
        imageUrl: `${imageUrl}?t=${t}`
      }
    } else {
      return {
        title: '分享标题参数缺少，请重新分享',
        path: `${sharePath}`,
        imageUrl: `${imageUrl}?t=${t}`
      }
    }
  }
})